package com.shudes.pt.builder;

import java.util.*;

import org.hibernate.*;
import org.hibernate.criterion.*;

import com.shudes.pt.container.*;
import com.shudes.pt.db.*;
import com.shudes.pt.pojo.*;
import com.shudes.util.*;

public class GamePlayerBuilder extends AbstractBuilder {

	public GamePlayerBuilder(SessionContext sc) {
		super(sc);
	}
	
	@SuppressWarnings("unchecked")
	public GamePlayerContainer forGame(Game g) { 
		List result; 
		Session session; 
				
		session = getSessionContext().getSession(); 
		session.beginTransaction();
		result = 
			session.createCriteria(GamePlayer.class)
			.add(Restrictions.eq("game", g)).list();
		session.getTransaction().commit();
		
		return new GamePlayerContainer(g, result); 
	}		
	
	@SuppressWarnings("unchecked")
	public GamePlayerContainerMap onDate(Date d) 
	{
		Session session;
		List<GamePlayer> result; 
		List<Game> games; 
				
		session = getSessionContext().getSession();
		
		games = new GameBuilder(getSessionContext()).forOnDay(d);
		
		session.beginTransaction();
		result = session.createCriteria(GamePlayer.class)
			.add(Restrictions.in("game", games)).list(); 
		session.getTransaction().commit();
						
		return new GamePlayerContainerMap(result); 
	}
	
	public GamePlayerContainerMap forDay(Player p, Date d)
	{
		Date start;
		Date end;
		Session session; 
		List result; 
		GamePlayerContainerMap map; 
		GamePlayer gp;
		Query q; 
		
		start = Dates.truncateDate(d);
		end = Dates.endOfDay(d); 
		
		session = getSessionContext().getSession();
		session.beginTransaction();
		
		q = session.createQuery(buildForDaySql()); 
		q.setLong("player", p.getId()); 
		q.setTimestamp("dateStart", start);
		q.setTimestamp("dateEnd", end); 
		result = q.list(); 
		
		System.out.println("result size=" + result.size()); 
		System.out.println("date = " + Dumper.INSTANCE.dump(start));
		System.out.println("date = " + Dumper.INSTANCE.dump(end)); 
		
//		session.getTransaction().commit();
		
		map  = new GamePlayerContainerMap();
		for(Object o : result) { 
			gp = (GamePlayer) o; 
			System.out.println(new Dumper().dump(gp));  
			map.addGamePlayer(gp); 			
		}
		
		return map; 
		
	}
	
	private String buildForDaySql()
	{
		return "select gp" 
			+ " from GamePlayer as gp inner join gp.game as game "  
			+ " where " 
			+ " gp.player = :player " 
			+ " and game.datePlayed >= :dateStart " 
			+ " and game.datePlayed <= :dateEnd"; 
	}
	
	

}
